package dayu.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author dayu
 * @create 2018/12/11 16:25
 * @Description
 */
public class ShiroUtils {
    public static Subject getSubject(String path){
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory(path);
        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        return subject;
    }

    public static void userLogin(Subject subject, UsernamePasswordToken token) {
        try {
            subject.login(token);
            System.out.println("是否认证："+subject.isAuthenticated());
        }catch (UnknownAccountException e){
            System.out.println("未知的账号："+e.getMessage());
        }catch (IncorrectCredentialsException e){
            System.out.println("账号密码错误："+e.getMessage());
        }catch (AuthenticationException e){
            System.out.println("认证异常："+e.getMessage());
        }
    }
}
